<?php

class PersonaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','neonato','calcularEdad','inscripcion'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
        
        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Persona the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Persona::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

        
        
	/**
	 * Performs the AJAX validation.
	 * @param Persona $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='persona-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        /**************************************************************************/
        /**************************************************************************/
        
        /**
	 * Manages all models.
	 */
        
	public function actionAdmin()
	{
		$model=new Persona('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_POST['Persona']))
			$model->attributes=$_POST['Persona'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
        
        
        
        public function actionInscripcion($id=null)
	{
           
          $transaction = Yii::app()->db->beginTransaction(); 
          try{
              
             $model=new Persona;
             
                if (!empty($id)){    
                    $model = $this->loadModel($id);

                    $model->localidad = $model->MiMunicipio->MiLocalidad->id;
                    
                    $departamento = Localidad::model()->findByPk($model->localidad);
                    $departamento_id = $departamento->id_departamento;
                    $model->departamento = $departamento_id;
                    $model->barrio = $model->id_barrio;
                    $model->municipio = $model->id_municipio;                
                }

                if(isset($_POST['Persona']))
                {       
                    $model->attributes=$_POST['Persona'];
                    $docBeneficiarios = $model->numero_documento;
                    $model->departamento = $_POST['Persona']['departamento'];
                    $model->localidad = $_POST['Persona']['localidad'];
                    $model->municipio = $_POST['Persona']['id_municipio'];
                    $model->barrio = $_POST['Persona']['id_barrio'];
                    
                        $criteria = new CDbCriteria();
                        $criteria->condition = "numero_documento LIKE :nro_doc";
                        $criteria->params = array(':nro_doc'=> $docBeneficiarios);
                        
                        $hayPersonas  = Persona::model()->findAll($criteria);
                    
                    if (!empty($hayPersonas)){
                          Yii::app()->user->setFlash('advertencia','Se encontraron inscripciones con el mismo numero de documento.');
                    }
                        
                    if($model->save()){               
                            $transaction->commit();
                            Yii::app()->user->setFlash('resultado_carga','bENEFICIARIO inSCRIPTO CON EXITO!!!');
                            $this->redirect(array('view','id'=>$model->id));
                    }else
                            $transaction->rollBack();  
                }

                
            $this->render('create',array(
                    'model'=>$model,
            ));
            
         }catch(CDbException $e)
         {
            $transaction->rollBack();
             
             if(!isset($_GET['ajax']))
                Yii::app()->user->setFlash('error','ERROR!!! No se puedo realizar la eliminacion!!!');
             else
                {
                 echo CJSON::encode(array(
                         'result'=>0,
                         'result_texto'=>'SE PRODUJO UN ERROR AL QUERER ',
                        ));
                    Yii::app()->end(); 
                    exit;
               }
        }       
       }
       
       /**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
        
        
        /*
        public function actionNeonato(){
            $fechaNac = '10-10-2014';
            $fechaHoy = '17-10-2014';
            $cantDias = 10;
            if (Persona::esNeonato($fechaNac, $fechaHoy, $cantDias))
                die("SIIIIII");
            else
                die("nooo");
       }
       */
        /*
            public function actionCalcularEdad(){
            $fechaNac = '14-12-2020';
            $fechaHoy = '29-01-2015';
            $edad = Persona::calcularEdad($fechaNac, $fechaHoy);
            print_r($edad);
        }*/
        
        
        

        
        
}
